package com.sskj.uboex.ui.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;

import com.github.tifezh.kchartlib.chart.BaseKChartAdapter;
import com.github.tifezh.kchartlib.chart.KChartView;
import com.github.tifezh.kchartlib.chart.draw.MainDraw;
import com.github.tifezh.kchartlib.chart.formatter.DateLFormatter;
import com.github.tifezh.kchartlib.chart.formatter.TimeFormatter;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.TimeFormatUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.StockCoinBean;
import com.sskj.uboex.R;
import com.sskj.uboex.bean.Stock;
import com.sskj.uboex.presenter.ChartPresenter;
import com.sskj.uboex.util.DataUtil;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

/**
 * ProjectName：new_bfex
 * DESC: (类描述)
 * Created by 李岩 on 2018/7/5 0005
 * updateName:(修改人名称)
 * updateTime:(修改时间)
 * updateDesc:(修改内容)
 */
public class ChartFragment extends BaseFragment<ChartPresenter> {
    @BindView(R.id.minute_kchartview)
    KChartView mMinuteKchartview;
    private KChartAdapter mAdapter;

    private String code;
    private Disposable mDisposable;
    private String timeCycle;
    private int count;
    private String newPrice;
    private boolean isUpdate;
    //

    /**
     * @param code 币种编码
     * @return
     */
    public static ChartFragment newInstance(String code, String timeCycle, boolean isCandle) {
        ChartFragment chartFragment = new ChartFragment();
        Bundle bundle = new Bundle();
        bundle.putString(Constans.CODE, code);
        bundle.putString(Constans.TIME_CYCLE, timeCycle);
        bundle.putBoolean(Constans.IS_CANDLE, isCandle);
        chartFragment.setArguments(bundle);
        return chartFragment;
    }

    public KChartView getKChartView() {
        return mMinuteKchartview;
    }

    @Override
    public int getLayoutId() {
        return R.layout.app_fragment_chart_view;
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
    }

    @Override
    public ChartPresenter getPresenter() {
        return new ChartPresenter();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        code = getArguments().getString(Constans.CODE);
        timeCycle = getArguments().getString(Constans.TIME_CYCLE);
        boolean isCandle = getArguments().getBoolean(Constans.IS_CANDLE, false);
        mMinuteKchartview.showLoading();
        mMinuteKchartview.setMainDownColor(R.color.app_999);
        mMinuteKchartview.setVolumeMaGone(true);
        mMinuteKchartview.setDrawTabView(false);
        mMinuteKchartview.setGridRows(3);
        mMinuteKchartview.setRedUpAndGreenDown(true);
        mMinuteKchartview.setGridLineColor(Color.parseColor("#e8e8e8"));
        mMinuteKchartview.setGridLineWidth(1f);
        mMinuteKchartview.setTextColor(Color.parseColor("#999999"));
        ((MainDraw)mMinuteKchartview.getMainDraw()).setSelectorTextColor(Color.WHITE);
        mMinuteKchartview.setGridColumns(2);
        mMinuteKchartview.setBreathColor(Color.parseColor("#e83030"));
        mMinuteKchartview.setShader(Color.parseColor("#806283eb"),Color.parseColor("#805e7bd8"),Color.parseColor("#334b65dd"),1000);
        mMinuteKchartview.setValueFormatter(v -> {
            if (code.toUpperCase().contains("USDT")) {
                return NumberUtil.keepMax(v, 4);
            }else {
                return NumberUtil.keepMax(v, 8);

            }
        });
        if (!isCandle) {
            mMinuteKchartview.setDrawMinuteStyle(true);
            mMinuteKchartview.setDateTimeFormatter(new TimeFormatter());
        } else {
            mMinuteKchartview.setDateTimeFormatter(new DateLFormatter());
        }
        mAdapter = new KChartAdapter();
        mMinuteKchartview.setAdapter(mAdapter);
        mPresenter.getStockInfo(timeCycle, code, false);
        time();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        mPresenter.getStockInfo(timeCycle, code, false);
    }

    /**
     * 开启定时刷新
     */
    private void time() {
        long initDelay = SystemClock.currentThreadTimeMillis() / 1000 % 60 + 2;

        mDisposable = Flowable.interval(initDelay, 20, TimeUnit.SECONDS)
                .subscribe(a -> {
                    if (mMinuteKchartview != null) {
                        mMinuteKchartview.showLoading();
                        mPresenter.getStockInfo(timeCycle, code, true);

                    }
                });
    }

    public void setChart(List<Stock> stockList, boolean update) {

        if (mMinuteKchartview != null) {
            mMinuteKchartview.hideLoading();
            if (stockList == null)
                return;
            if (update) {
                isUpdate = true;
                count = 0;
                Flowable.fromIterable(stockList)
                        .takeUntil(item -> {
                            return isSameTime(item.getDate());
                        })
                        .subscribe(item -> {
                            count++;
                        }, e -> {
                        });
//                System.out.println(App.INSTANCE.getString(R.string.strChartFragment1));
//                Flowable.fromIterable(stockList.subList(0, 5))
//                        .map(item -> TimeFormatUtil.SF_FORMAT_D.format(new Date(item.getDate())))
//                        .subscribe(out -> System.out.println(out));
//                System.out.println(App.INSTANCE.getString(R.string.strChartFragment2) + TimeFormatUtil.SF_FORMAT_D.format(mAdapter.getDate(mAdapter.getCount() - 1)));
//                System.out.println("cout" + count);
                if (count > 1 && count != mAdapter.getCount()) {
                    Collections.reverse(stockList);
                    DataUtil.calculate(stockList);
                    if (!TextUtils.isEmpty(newPrice)) {
                        stockList.get(stockList.size() - 1).setClosePrice(Double.valueOf(NumberUtil.keep4(newPrice)));
                    }
                    List<Stock> stocks = stockList.subList(stockList.size() - count + 1, stockList.size());
                    mAdapter.addNewData(stocks);
                }
                isUpdate = false;
            } else {
                Collections.reverse(stockList);
                DataUtil.calculate(stockList);
                mAdapter.datas.clear();
                mAdapter.updateData(stockList);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
        DisposUtil.close(mDisposable);
    }

    /**
     * 长链接  更新当前分时图
     *
     * @param
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upDate(StockCoinBean.StockProductVOBean stockProductVOBean) {
        if (!TextUtils.isEmpty(stockProductVOBean.getPrice())) {
            if (mAdapter.getCount() > 0) {
                if (stockProductVOBean.getCode().equals(code)) {
                    mAdapter.changeLastItemClosePrice(new BigDecimal(stockProductVOBean.getPrice()).floatValue());
//
//                    System.out.println(App.INSTANCE.getString(R.string.strChartFragment4)+stockProductVOBean.getTime());
//                    System.out.println(App.INSTANCE.getString(R.string.strChartFragment2) + TimeFormatUtil.SF_FORMAT_D.format(mAdapter.getDate(mAdapter.getCount() - 1)));
//                   if (isLastNewData(stockProductVOBean)) {
//                       System.out.println(App.INSTANCE.getString(R.string.strChartFragment6));
//                       mAdapter.changeLastItemClosePrice(new BigDecimal(stockProductVOBean.getPrice()).floatValue());
//                   }else {
//                       System.out.println(App.INSTANCE.getString(R.string.strChartFragment7));
//                       if (!isUpdate) {
//                           mPresenter.getStockInfo(timeCycle, code, true);
//                       }
//                   }
                }
            }
        }
    }

    private boolean isLastNewData(StockCoinBean.StockProductVOBean stockProductVOBean) {
        try {
            String time = stockProductVOBean.getDate() + " " + stockProductVOBean.getTime();
            Date newDate = TimeFormatUtil.SF_FORMAT_E.parse(time);
            long compareTime = newDate.getTime();
            return isSameTime(compareTime);
        } catch (ParseException e) {
            return false;
        }
    }

    private boolean isSameTime(long compareTime) {
        long dividerTime = 1;
        switch (timeCycle) {
            case "minute":
                dividerTime = 1000 * 60;
                break;
            case "minute15":
                dividerTime = 1000 * 60 * 15;
                break;
            case "minute30":
                dividerTime = 1000 * 60 * 30;
                break;
            case "minute60":
                dividerTime = 1000 * 60 * 60;
                break;
            case "day":
                dividerTime = 1000 * 60 * 60 * 24;
                break;
        }
        return compareTime / dividerTime == mAdapter.getDatas().get(mAdapter.getCount() - 1).getDate() / dividerTime;
    }

    /**
     * 数据适配器
     * Created by tifezh on 2016/6/18.
     */

    public class KChartAdapter extends BaseKChartAdapter {

        private List<Stock> datas = new ArrayList<>();

        public KChartAdapter() {

        }

        public List<Stock> getDatas() {
            return datas;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            return datas.get(position);
        }

        @Override
        public Date getDate(int position) {
            return new Date(datas.get(position).getDate());
        }

        /**
         * 向头部添加数据
         */
        public void addNewData(List<Stock> data) {
            if (data != null && !data.isEmpty()) {
                datas.addAll(data);
                notifyItemRangeInsertedToLast();
            }
        }


        /**
         * 向尾部添加数据
         */
        public void updateData(List<Stock> data) {
            if (data != null && !data.isEmpty()) {
                datas.clear();
                datas.addAll(0, data);
                notifyDataSetChanged();
            }
        }

        /**
         * 改变某个点的值
         */
        public void changeLastItemClosePrice(float closePrice) {
            notifyLastItemChanged(closePrice);
        }

    }
}
